//
//  MemberCenterViewController.m
//  
//
//  Created by tmosport on 14-4-16.
//  Copyright (c) 2014年 tmosport. All rights reserved.
//

#import "MemberCenterViewController.h"
#import "logOnViewController.h"
#import "ZPUserModel.h"
#import "myOrderListViewController.h"
#import "JSBadgeView.h"
@interface MemberCenterViewController ()
{
    JSBadgeView *messageCountView;
    JSBadgeView *sureCountView;
    JSBadgeView *commentCountView;
}
@property (nonatomic) BOOL isLogin;
@property (nonatomic,strong) NSArray *logResult;
@property (nonatomic,copy)NSString *memberId;
@property (nonatomic,copy)NSString *atoken;
@property (nonatomic,strong)NSString *userName;
@property (nonatomic,strong) UIView *baseHeader;

@end

@implementation MemberCenterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


-(void)viewWillAppear:(BOOL)animated {
//    self.navigationController.navigationBar.translucent = YES;
//    self.navigationController.navigationBar.alpha = 0.95;
//    [self.tableView setContentInset:UIEdgeInsetsMake(0, self.tableView.contentInset.left, self.tableView.contentInset.bottom, self.tableView.contentInset.right)];
    //checkLogin
    [[NSNotificationCenter defaultCenter] postNotificationName:StringForCheckLogin object:nil];
    [self checkLogin];
    [self initBadge];//初始化气泡
}
-(void)viewWillDisappear:(BOOL)animated {
//    self.navigationController.navigationBar.alpha = 1;
//    self.navigationController.navigationBar.translucent = NO;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"个人中心";
    self.automaticallyAdjustsScrollViewInsets = NO;

    [self initHeaderView];
    [self setMemberVariable];
    self.tableView.backgroundColor = ColorFromRGB(0xF6F6F6);
    self.tableView.separatorColor = ColorFromRGB(0xDBDBDB);
//    _buttonsView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"buttonsViewBG"]];
}

-(void)setMemberVariable {
    sureCountView = [[JSBadgeView alloc] initWithParentView:_sureBt alignment:JSBadgeViewAlignmentTopCenter];
    sureCountView.badgePositionAdjustment = CGPointMake(18, 15);
    sureCountView.userInteractionEnabled = NO;
    sureCountView.clipsToBounds = YES;
    sureCountView.backgroundColor = [UIColor clearColor];
    sureCountView.badgeBackgroundColor = [UIColor whiteColor];
    sureCountView.hidden = YES;
    sureCountView.badgeText = @"0";
    sureCountView.badgeTextColor = [UIColor redColor];
    
    commentCountView = [[JSBadgeView alloc] initWithParentView:_commentBtn alignment:JSBadgeViewAlignmentTopCenter];
    commentCountView.badgePositionAdjustment = CGPointMake(18, 15);
    commentCountView.userInteractionEnabled = NO;
    commentCountView.clipsToBounds = YES;
    commentCountView.backgroundColor = [UIColor clearColor];
    commentCountView.badgeBackgroundColor = [UIColor whiteColor];
    commentCountView.hidden = YES;
    commentCountView.badgeText = @"0";
    commentCountView.badgeTextColor = [UIColor redColor];
    
    messageCountView = [[JSBadgeView alloc] initWithParentView:_messageBtn alignment:JSBadgeViewAlignmentTopCenter];
    messageCountView.badgePositionAdjustment = CGPointMake(18, 15);
    messageCountView.userInteractionEnabled = NO;
    messageCountView.clipsToBounds = YES;
    messageCountView.backgroundColor = [UIColor clearColor];
    messageCountView.badgeBackgroundColor = [UIColor whiteColor];
    messageCountView.hidden = YES;
    messageCountView.badgeText = @"0";
    messageCountView.badgeTextColor = [UIColor redColor];
    
    
    [self.navigationController.navigationBar setBackIndicatorImage:
     [UIImage imageNamed:@"return"]];
    [self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:
     [UIImage imageNamed:@"return"]];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil];
}

-(void)leftBarbuttonItemClicked:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)initHeaderView{
    _baseHeader  = [UIView new];
    CGRect baseFrame = _userView.frame;
    _baseHeader.frame = baseFrame;
    UILabel *welcome = [[UILabel alloc]initWithFrame:CGRectMake(baseFrame.size.width/2 - 100,4, 200, 16)];
    welcome.textAlignment = NSTextAlignmentCenter;
    welcome.font = [UIFont fontWithName:@"STHeitiSC-Medium-BOLD" size:16];
    welcome.text= @"Hi,欢迎来到奢品特卖!";
    welcome.textColor = [UIColor whiteColor];
    _baseHeader.backgroundColor = [UIColor clearColor];
    UIButton *loginButton = [[UIButton alloc]initWithFrame:CGRectMake(baseFrame.size.width/2 - 55,33, 110, 30)];
    [loginButton setTitle:@"登录 / 注册" forState:UIControlStateNormal];
    [loginButton setTitle:@"登录 / 注册" forState:UIControlStateHighlighted];
    loginButton.titleLabel.font = [UIFont fontWithName:@"STHeitiSC-Light" size:16];
    //                loginButton.titleLabel.textColor = [UIColor blackColor];
    [loginButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [loginButton setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    [loginButton.layer setCornerRadius:5.0];
    [loginButton setBackgroundColor:[UIColor whiteColor]];
    [loginButton addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    
    [_baseHeader addSubview:loginButton];
    [_baseHeader addSubview:welcome];
    [self.tableView.tableHeaderView addSubview:_baseHeader];
    [self.tableView.tableHeaderView bringSubviewToFront:_baseHeader];
    _userView.hidden = YES;
}

- (void)login{
    logOnViewController *loginVC = (logOnViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"logOnViewController"];
    UINavigationController *navigationVC = [[UINavigationController alloc]initWithRootViewController:loginVC];
    
   navigationVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    navigationVC.navigationBar.tintColor = [UIColor blackColor];
    // present
    [self presentViewController:navigationVC animated:YES completion:nil];
}

- (void)viewDidLayoutSubviews
{

}

-(void)checkLogin {
    if ([CheckLoginObject isLogin]) {
        
        NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
        NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
        self.isLogin = YES;//登陆过程标记
        _baseHeader.hidden = YES;
        _userView.hidden = NO;
        _memberId = [dataDic valueForKey:@"memberId"];
        _atoken = [dataDic valueForKey:@"token"];
        _userName =[dataDic valueForKey:@"userName"];
        [self initMyZhenPin];
    } else {
        _isLogin = NO; //默认标记
        _baseHeader.hidden = NO;
        _userView.hidden = YES;
    }
}

- (void)initMyZhenPin
{
        NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
        NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
        _memberId = dataDic[@"memberId"];
        _atoken = dataDic[@"token"];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSDictionary *params = @{@"memberid": _memberId,
                                 @"access_token": _atoken};
        
        [manager POST:APIURL@"myzhenpin/initMyZhenPin.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary* _myZhenPin = (NSDictionary *)responseObject;
            if ([_myZhenPin valueForKey:@"level"]) {
                self.isLogin = YES;
                UILabel *showName = (UILabel *)[_userView viewWithTag:1001];
                UILabel *showPoint = (UILabel *)[_userView viewWithTag:1003];
                UILabel *showLevel = (UILabel *)[_userView viewWithTag:1002];
                showName.text = _userName;
                showLevel.text = [NSString stringWithFormat:@"会员等级: %@",_myZhenPin[@"level"]];
                showPoint.text = [NSString stringWithFormat:@"当前积分: %@",_myZhenPin[@"score"]];
                if ([_myZhenPin[@"orderCount"] integerValue] > 0) {
                    sureCountView.hidden = NO;
                    sureCountView.badgeText = [NSString stringWithFormat:@"%@",_myZhenPin[@"orderCount"]];
                }else{
                    sureCountView.hidden = YES;
                    sureCountView.badgeText = @"0";
                }
                if ([_myZhenPin[@"unevalCount"] integerValue] > 0) {
                    commentCountView.hidden = NO;
                    commentCountView.badgeText = [NSString stringWithFormat:@"%@",_myZhenPin[@"unevalCount"]];
                }else{
                    commentCountView.hidden = YES;
                    commentCountView.badgeText = @"0";
                }
                if ([_myZhenPin[@"unreadCount"] integerValue] > 0) {
                    messageCountView.hidden = NO;
                    messageCountView.badgeText = [NSString stringWithFormat:@"%@",_myZhenPin[@"unreadCount"]];
                }else{
                    messageCountView.hidden = YES;
                    messageCountView.badgeText = @"0";
                }
                
            }else{
                
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            self.isLogin = NO;//接口握手失败标记
        }];

}

-(void)initBadge{
    //非登陆状态下清理
    if (!_isLogin) {
        sureCountView.hidden = YES;
        sureCountView.badgeText = @"0";
        commentCountView.hidden = YES;
        commentCountView.badgeText = @"0";
        messageCountView.hidden = YES;
        messageCountView.badgeText = @"0";
        
    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"waitForSureSegue"]) {
        myOrderListViewController *destVC = segue.destinationViewController;
        destVC.memberId  = _memberId;
        destVC.token    = _atoken;
        destVC.type =@"3";
        destVC.hidesBottomBarWhenPushed = YES;
    } else {
//        ([segue.identifier isEqualToString:@"waitForRateSegue"]) {
        myOrderListViewController *destVC = segue.destinationViewController;
        destVC.memberId  = _memberId;
        destVC.token    = _atoken;
        destVC.hidesBottomBarWhenPushed = YES;
    }
    
    
    
}

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    BOOL loginStatus;
    if ([identifier isEqualToString:@"aboutUs"]) {
        loginStatus = YES;
    } else {
        if (_isLogin) {
            loginStatus =  YES;
        }else{
            [self login];
            loginStatus =  NO;
        }
    }
   
    return loginStatus;
}


- (BOOL)validateEmail:(NSString *)userName{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:userName];
}

- (BOOL)validateMobile:(NSString *)userName
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[0-9])|(17[0-9])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:userName];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
